<template>
  <div class="simple-paint-test">
    <div class="header">
      <h2>简单涂色同步测试</h2>
      <div class="connection-status" :class="{ connected: isConnected }">
        {{ isConnected ? '已连接' : '未连接' }}
      </div>
    </div>

    <div class="controls">
      <el-button @click="connect" :disabled="isConnected" type="primary">
        连接
      </el-button>
      <el-button @click="disconnect" :disabled="!isConnected" type="danger">
        断开
      </el-button>
      <el-button @click="joinRoom" :disabled="!isConnected" type="success">
        加入房间
      </el-button>
             <el-button @click="sendTestPaint" :disabled="!isConnected" type="warning">
         发送测试涂色
       </el-button>
       <el-button @click="testConnection" :disabled="!isConnected" type="primary">
         测试连接
       </el-button>
       <el-button @click="runDiagnostic" type="warning">
         运行诊断
       </el-button>
       <el-button @click="clearCanvas" type="info">
         清空画布
       </el-button>
    </div>

    <div class="canvas-container">
      <canvas
        ref="canvasRef"
        width="600"
        height="400"
        class="paint-canvas"
        @mousedown="startDrawing"
        @mousemove="draw"
        @mouseup="stopDrawing"
        @mouseleave="stopDrawing"
      ></canvas>
    </div>

    <div class="info-panel">
      <div class="info-item">
        <span>连接状态:</span>
        <span :class="{ connected: isConnected }">{{ isConnected ? '已连接' : '未连接' }}</span>
      </div>
      <div class="info-item">
        <span>房间:</span>
        <span>{{ roomId }}</span>
      </div>
      <div class="info-item">
        <span>玩家ID:</span>
        <span>{{ playerId }}</span>
      </div>
      <div class="info-item">
        <span>发送动作:</span>
        <span>{{ sentCount }}</span>
      </div>
      <div class="info-item">
        <span>接收动作:</span>
        <span>{{ receivedCount }}</span>
      </div>
    </div>

    <div class="log-panel">
      <h3>事件日志</h3>
      <div class="log-content">
        <div v-for="log in logs.slice(-10)" :key="log.id" class="log-item" :class="log.type">
          <span class="log-time">{{ log.time }}</span>
          <span class="log-message">{{ log.message }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { createSignalRService } from '@/services/socketService'
import { ElMessage } from 'element-plus'
import syncDiagnostic from '@/utils/syncDiagnostic'

// 状态变量
const isConnected = ref(false)
const roomId = ref('test-room-001')
const playerId = ref('player-' + Math.random().toString(36).substr(2, 9))
const sentCount = ref(0)
const receivedCount = ref(0)
const logs = ref([])

// 画布相关
const canvasRef = ref(null)
const ctx = ref(null)
const isDrawing = ref(false)
const lastX = ref(0)
const lastY = ref(0)

// SignalR服务
const signalRService = createSignalRService({})

// 添加日志
function addLog(type, message) {
  logs.value.push({
    id: Date.now() + Math.random(),
    type,
    message,
    time: new Date().toLocaleTimeString()
  })
  
  // 限制日志数量
  if (logs.value.length > 50) {
    logs.value.shift()
  }
}

// 连接
async function connect() {
  try {
    addLog('info', '正在连接...')
    await signalRService.connect()
    isConnected.value = true
    addLog('success', '连接成功')
    ElMessage.success('连接成功')
  } catch (error) {
    addLog('error', '连接失败: ' + error.message)
    ElMessage.error('连接失败: ' + error.message)
  }
}

// 断开连接
async function disconnect() {
  try {
    await signalRService.disconnect()
    isConnected.value = false
    addLog('info', '已断开连接')
    ElMessage.info('已断开连接')
  } catch (error) {
    addLog('error', '断开连接失败: ' + error.message)
  }
}

// 加入房间
async function joinRoom() {
  try {
    addLog('info', '正在加入房间: ' + roomId.value)
    await signalRService.joinRoom(roomId.value, playerId.value, '测试玩家', '#ff0000')
    addLog('success', '已加入房间')
    ElMessage.success('已加入房间')
  } catch (error) {
    addLog('error', '加入房间失败: ' + error.message)
    ElMessage.error('加入房间失败: ' + error.message)
  }
}

// 测试连接
function testConnection() {
  addLog('info', '开始测试连接...')
  
  // 检查连接状态
  const isConnected = signalRService.getConnectionStatus()
  addLog('info', `连接状态: ${isConnected ? '已连接' : '未连接'}`)
  
  // 检查连接ID
  const connectionId = signalRService.getConnectionId()
  addLog('info', `连接ID: ${connectionId || '无'}`)
  
  // 检查消息队列状态
  const queueStatus = signalRService.getMessageQueueStatus()
  addLog('info', `消息队列: ${queueStatus.queueLength}/${queueStatus.maxQueueSize}`)
  
  // 发送ping测试
  signalRService.ping().then(() => {
    addLog('success', 'Ping测试成功')
  }).catch(error => {
    addLog('error', `Ping测试失败: ${error.message}`)
  })
  
  ElMessage.info('连接测试完成，查看日志')
}

// 运行完整诊断
async function runDiagnostic() {
  addLog('info', '开始运行完整诊断...')
  ElMessage.info('开始诊断，请查看日志')
  
  try {
    const results = await syncDiagnostic.fullDiagnostic(
      signalRService,
      canvasRef,
      roomId.value,
      playerId.value
    )
    
    addLog('success', `诊断完成: ${results.summary.totalIssues}个问题`)
    
    if (results.summary.criticalIssues > 0) {
      ElMessage.error(`发现 ${results.summary.criticalIssues} 个严重问题`)
    } else if (results.summary.totalIssues > 0) {
      ElMessage.warning(`发现 ${results.summary.totalIssues} 个问题`)
    } else {
      ElMessage.success('诊断通过，同步应该正常工作')
    }
    
    // 导出诊断报告
    syncDiagnostic.exportDiagnosticReport()
    
  } catch (error) {
    addLog('error', `诊断失败: ${error.message}`)
    ElMessage.error('诊断失败')
  }
}

// 发送测试涂色
function sendTestPaint() {
  const x = Math.floor(Math.random() * 600)
  const y = Math.floor(Math.random() * 400)
  const color = '#' + Math.floor(Math.random()*16777215).toString(16)
  
  addLog('info', `准备发送测试涂色: (${x}, ${y}) 颜色: ${color}`)
  
  try {
    signalRService.sendPaintAction(roomId.value, playerId.value, x, y, color, 10, 'brush')
    sentCount.value++
    addLog('success', `测试涂色动作已发送`)
    ElMessage.success('测试涂色动作已发送')
  } catch (error) {
    addLog('error', `发送测试涂色失败: ${error.message}`)
    ElMessage.error('发送测试涂色失败')
  }
}

// 清空画布
function clearCanvas() {
  if (!ctx.value) return
  
  ctx.value.fillStyle = '#ffffff'
  ctx.value.fillRect(0, 0, 600, 400)
  
  addLog('info', '画布已清空')
  ElMessage.info('画布已清空')
}

// 画布绘制
function startDrawing(event) {
  isDrawing.value = true
  const rect = canvasRef.value.getBoundingClientRect()
  lastX.value = event.clientX - rect.left
  lastY.value = event.clientY - rect.top
}

function draw(event) {
  if (!isDrawing.value) return
  
  const rect = canvasRef.value.getBoundingClientRect()
  const x = event.clientX - rect.left
  const y = event.clientY - rect.top
  
  // 绘制
  ctx.value.strokeStyle = '#ff0000'
  ctx.value.lineWidth = 5
  ctx.value.lineCap = 'round'
  ctx.value.beginPath()
  ctx.value.moveTo(lastX.value, lastY.value)
  ctx.value.lineTo(x, y)
  ctx.value.stroke()
  
  // 发送涂色动作（包含起始点）- 立即发送
  const paintData = {
    x: Math.round(x),
    y: Math.round(y),
    color: '#ff0000',
    brushSize: 5,
    tool: 'brush',
    fromX: Math.round(lastX.value),
    fromY: Math.round(lastY.value)
  }
  
  // 立即发送，不使用队列
  try {
    signalRService.sendPaintActionWithData(roomId.value, playerId.value, paintData)
    sentCount.value++
  } catch (error) {
    console.error('发送失败:', error)
  }
  
  lastX.value = x
  lastY.value = y
}

function stopDrawing() {
  isDrawing.value = false
}

// 处理收到的涂色动作
function handlePaintActionReceived(paintData) {
  console.log('收到涂色动作:', paintData)
  console.log('paintData类型:', typeof paintData)
  console.log('paintData键:', Object.keys(paintData || {}))
  console.log('paintData完整内容:', JSON.stringify(paintData, null, 2))
  
  addLog('info', `收到涂色动作，类型: ${typeof paintData}`)
  addLog('info', `paintData键: ${Object.keys(paintData || {}).join(', ')}`)
  
  receivedCount.value++
  
  if (!ctx.value) {
    addLog('error', 'Canvas context不可用')
    return
  }
  
  // 检查数据是否有效
  if (!paintData || typeof paintData !== 'object') {
    addLog('error', '收到的涂色动作数据无效')
    return
  }
  
  // 使用正确的键名（后端发送的是小写）
  const { x, y, tool, color, brushSize } = paintData
  
  addLog('info', `收到涂色动作: (${x}, ${y}) 颜色: ${color} 工具: ${tool}`)
  
  // 检查是否是自己的动作
  if (paintData.playerId === playerId.value) {
    addLog('info', '收到自己的涂色动作')
  } else {
    addLog('info', `收到玩家 ${paintData.playerId} 的涂色动作`)
  }
  
  if (tool === 'brush') {
    ctx.value.strokeStyle = color
    ctx.value.lineWidth = brushSize
    ctx.value.lineCap = 'round'
    ctx.value.lineJoin = 'round'
    
    if (paintData.fromX !== undefined && paintData.fromY !== undefined) {
      // 绘制线条（从上一个点到当前点）
      ctx.value.beginPath()
      ctx.value.moveTo(paintData.fromX, paintData.fromY)
      ctx.value.lineTo(x, y)
      ctx.value.stroke()
      addLog('success', '画笔线条已绘制')
    } else {
      // 绘制单个点
      ctx.value.fillStyle = color
      ctx.value.beginPath()
      ctx.value.arc(x, y, brushSize / 2, 0, 2 * Math.PI)
      ctx.value.fill()
      addLog('success', '画笔点已绘制')
    }
  } else if (tool === 'eraser') {
    ctx.value.strokeStyle = '#ffffff'
    ctx.value.lineWidth = brushSize
    ctx.value.lineCap = 'round'
    ctx.value.lineJoin = 'round'
    
    if (paintData.fromX !== undefined && paintData.fromY !== undefined) {
      // 绘制橡皮擦线条
      ctx.value.beginPath()
      ctx.value.moveTo(paintData.fromX, paintData.fromY)
      ctx.value.lineTo(x, y)
      ctx.value.stroke()
      addLog('success', '橡皮擦线条已绘制')
    } else {
      // 绘制橡皮擦点
      ctx.value.fillStyle = '#ffffff'
      ctx.value.beginPath()
      ctx.value.arc(x, y, brushSize / 2, 0, 2 * Math.PI)
      ctx.value.fill()
      addLog('success', '橡皮擦点已绘制')
    }
  } else if (tool === 'clear') {
    ctx.value.fillStyle = '#ffffff'
    ctx.value.fillRect(0, 0, 600, 400)
    addLog('success', '画布已清空')
  }
}

// 初始化
onMounted(() => {
  // 初始化画布
  const canvas = canvasRef.value
  if (canvas) {
    ctx.value = canvas.getContext('2d')
    ctx.value.fillStyle = '#ffffff'
    ctx.value.fillRect(0, 0, 600, 400)
  }
  
  // 设置事件监听
  signalRService.on('Connected', (data) => {
    addLog('success', 'SignalR连接成功')
  })
  
  signalRService.on('PaintActionReceived', (data) => {
    handlePaintActionReceived(data)
  })
  
  signalRService.on('PlayerJoined', (data) => {
    addLog('info', `玩家加入: ${data.Nickname}`)
  })
  
  signalRService.on('PlayerLeft', (data) => {
    addLog('info', `玩家离开: ${data.PlayerId}`)
  })
  
  addLog('info', '页面已加载')
})

onUnmounted(() => {
  // 清理事件监听
  signalRService.off('Connected')
  signalRService.off('PaintActionReceived')
  signalRService.off('PlayerJoined')
  signalRService.off('PlayerLeft')
})
</script>

<style scoped>
.simple-paint-test {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #333;
}

.connection-status {
  padding: 8px 16px;
  border-radius: 20px;
  background: #ff4d4f;
  color: white;
  font-weight: bold;
}

.connection-status.connected {
  background: #52c41a;
}

.controls {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.canvas-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.paint-canvas {
  border: 2px solid #ddd;
  border-radius: 8px;
  cursor: crosshair;
  background: white;
}

.info-panel {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 8px;
  background: white;
  border-radius: 4px;
  font-size: 14px;
}

.info-item .connected {
  color: #52c41a;
  font-weight: bold;
}

.log-panel {
  background: white;
  border: 1px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
}

.log-panel h3 {
  margin: 0;
  padding: 15px;
  background: #f8f9fa;
  border-bottom: 1px solid #ddd;
}

.log-content {
  height: 300px;
  overflow-y: auto;
  padding: 10px;
}

.log-item {
  display: flex;
  gap: 10px;
  margin-bottom: 5px;
  padding: 5px;
  border-radius: 4px;
  font-size: 12px;
}

.log-item.info {
  background: #e6f7ff;
  color: #1890ff;
}

.log-item.success {
  background: #f6ffed;
  color: #52c41a;
}

.log-item.error {
  background: #fff2f0;
  color: #ff4d4f;
}

.log-time {
  color: #999;
  min-width: 80px;
}

.log-message {
  flex: 1;
}
</style>
